package com.cangxuan.app.ui.user;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.R;
import com.cangxuan.app.entity.Bill;
import com.cangxuan.app.ui.BaseActivity;
import com.cangxuan.app.utils.DeviceUtils;
import com.cangxuan.app.utils.HttpUtils;
import com.google.android.material.tabs.TabLayout;

import java.net.HttpURLConnection;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Author: 彭伟辰
 * Activity: 联动支付页面
 * Layout: activity_linkage_payment
 */
public class LinkagePaymentActivity extends BaseActivity {
    Handler handler = new Handler();
    Button buttonAccountRecharge;//账号充值按钮
    Button buttonAccountWithdrawal;//账号提现按钮
    Spinner spinnerMonth;
    Spinner spinnerYear;
    TabLayout paymentTab;
    TextView paymentExpenditureTxt;//总支出
    TextView paymentIncomeTxt;//总收入

    class BillAdapter extends BaseAdapter {

        private List<Bill> billList;

        public BillAdapter(List<Bill> billList) {
            this.billList = billList;
        }

        public void setBillList(List<Bill> billList) {
            this.billList = billList;
        }

        @Override
        public int getCount() {
            return billList.size();
        }

        @Override
        public Object getItem(int i) {
            return billList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return billList.get(i).getId();
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            //声明视图持有类实例
            ViewHolder viewHolder;
            if (view == null) {
                //实例view对象
                view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.pay_whole_list_item, viewGroup, false);
                //当ListView第一次获取项的视图时
                viewHolder = new ViewHolder();
                //给viewHolder中的属性（控件）进行初始化
                viewHolder.paymentWholeItemStateText = view.findViewById(R.id.payment_whole_item_state);
                viewHolder.paymentWholeItemDataTimeText = view.findViewById(R.id.payment_whole_item_datatime);
                viewHolder.paymentWholeItemPriceText = view.findViewById(R.id.payment_whole_item_price);
                viewHolder.paymentWholeOrderNoText = view.findViewById(R.id.payment_whole_Order_No);
//                viewHolder.btnArticleShow = view.findViewById(R.id.btn_article_show);
                //将viewHolder设置在view的tag属性中，用于下一次getView时，即可从view的tag属性中获取。
                view.setTag(viewHolder);
            } else {
                //当ListView后面再获取项的视图时
                viewHolder = (ViewHolder) view.getTag();
            }
            //先取出对应下标的Article
            Bill bill = billList.get(i);
            //给viewHolder中的控件绑定数据
            if(bill.getState() == 0){
                viewHolder.paymentWholeItemStateText.setTextColor(Color.parseColor("#FF4500"));
            }else {
                viewHolder.paymentWholeItemStateText.setTextColor(Color.parseColor("#808080"));
            }
            viewHolder.paymentWholeItemStateText.setText(bill.getState() == 0 ? "支出" : "收入");
            viewHolder.paymentWholeItemDataTimeText.setText(bill.getLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            viewHolder.paymentWholeItemPriceText.setText(bill.getPrice().toString());
            viewHolder.paymentWholeOrderNoText.setText(bill.getOrderNo());
            return view;
        }

        /**
         * 视图持有类，
         * 该类的属性会包含ListView的项里面需要动态设置值的控件
         */
        class ViewHolder {
            TextView paymentWholeItemStateText;
            TextView paymentWholeItemDataTimeText;
            TextView paymentWholeItemPriceText;
            TextView paymentWholeOrderNoText;
        }

//        /**
//         * 添加数据
//         * @param article
//         */
//        public void add(Article article) {
//            articleList.add(article);
//            //通知适配器，数据源修改了
//            notifyDataSetChanged();
//        }
    }

    ListView listviewBill;
    TextView txtNoData;
    LinearLayout payment_listLoading;
    List<String> spYear;//年份数据源
    int year = Calendar.getInstance().get(Calendar.YEAR);//当前年份
    ArrayAdapter<String> yearArrayAdapter;//年份适配器

    List<Bill> billList;
    BillAdapter billAdapter;
    Button bu;
    JSONObject jsonObjectWh = new JSONObject();//请求体
    Map<String, String> header = new HashMap<>();//请求头

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_linkage_payment);
        setTitle("联动支付");
        listviewBill = findViewById(R.id.payment_list);
        txtNoData = findViewById(R.id.txtNoData);
        payment_listLoading = findViewById(R.id.payment_listLoading);
        spinnerMonth = findViewById(R.id.payment_month_sp);//月份spinner
        buttonAccountRecharge = findViewById(R.id.account_recharge);
        buttonAccountWithdrawal = findViewById(R.id.account_withdrawal);
        paymentIncomeTxt=findViewById(R.id.payment_income);//绑定总收入
        paymentExpenditureTxt=findViewById(R.id.payment_expenditure);//绑定总支出
        spinnerYear=findViewById(R.id.payment_year_sp);//年份spinner
        paymentTab=findViewById(R.id.payment_tabHead);
        spYear=Arrays.asList((year-2)+"年",(year-1)+"年",year+"年");//年份列表
        yearArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, spYear);
        spinnerYear.setAdapter(yearArrayAdapter);
        spinnerYear.setSelection(2);
        spinnerMonth.setSelection(Calendar.getInstance().get(Calendar.MONTH));
        billList = new ArrayList<>();
        billAdapter = new BillAdapter(billList);
        listviewBill.setAdapter(billAdapter);
        header.put("Authorization", ""+DeviceUtils.getDeviceID());
        jsonObjectWh.put("state", ""+-1);
        jsonObjectWh.put("year",""+year);
        jsonObjectWh.put("month",Calendar.getInstance().get(Calendar.MONTH)+1);
        Log.i("onCreate: ","jsonObjectWh:"+jsonObjectWh);
        sumTotal(jsonObjectWh,header,paymentExpenditureTxt,"sumExpenditure");
        sumTotal(jsonObjectWh,header,paymentIncomeTxt,"sumRevenue");
        ReBillAdapter(jsonObjectWh, billList, header);
        paymentTab.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()){
                    case 0:
                        jsonObjectWh.put("state", -1);
                        ReBillAdapter(jsonObjectWh, billList, header);
                        break;
                    case 1:
                        jsonObjectWh.put("state", 1);
                        ReBillAdapter(jsonObjectWh, billList, header);
                        break;
                    case 2:
                        jsonObjectWh.put("state", 0);
                        ReBillAdapter(jsonObjectWh, billList, header);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        spinnerYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            boolean a=true;
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
               if(a){
                   a=false;
                   return;
               }
                String a = adapterView.getAdapter().getItem(i).toString();
                String result = Pattern.compile("[^0-9]").matcher(a).replaceAll("");
                jsonObjectWh.put("year",result);
                sumTotal(jsonObjectWh,header,paymentExpenditureTxt,"sumExpenditure");
                sumTotal(jsonObjectWh,header,paymentIncomeTxt,"sumRevenue");
                ReBillAdapter(jsonObjectWh, billList, header);
                Log.i( "onItemSelected: ","执行了spinnerYear方法");
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        spinnerMonth.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            boolean a=true;
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
               if(a){
                   a=false;
                   return;
               }
                String a = adapterView.getAdapter().getItem(i).toString();
                String result = Pattern.compile("[^0-9]").matcher(a).replaceAll("");
                jsonObjectWh.put("month",result);
                sumTotal(jsonObjectWh,header,paymentExpenditureTxt,"sumExpenditure");
                sumTotal(jsonObjectWh,header,paymentIncomeTxt,"sumRevenue");
                ReBillAdapter(jsonObjectWh, billList, header);
                Log.i( "onItemSelected: ","执行了spinnermonth方法");
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        buttonAccountRecharge.setOnClickListener(view -> {
            Intent intent = new Intent(this, RechargeActivity.class);
            startActivity(intent);
        });
        buttonAccountWithdrawal.setOnClickListener(view -> {
            Intent intent = new Intent(this, WithdrawalsActivity.class);
            startActivity(intent);
        });
    }

    public void ReBillAdapter(JSONObject jsonObject, List<Bill> billList, Map<String, String> header) {
        billList.clear();
        billAdapter.notifyDataSetChanged();
        listviewBill.setVisibility(View.GONE);
        txtNoData.setVisibility(View.GONE);
        payment_listLoading.setVisibility(View.VISIBLE);

        Thread thread = new Thread(() -> {
            String post = HttpUtils.post("/api/bills/list", header, jsonObject.toJSONString());
            Log.i("ReBillAdapter: ", post);
            JSONObject jsonResponse = JSONObject.parseObject(post);
            if (jsonResponse == null) {
                handler.post(()->{
                    Toast.makeText(context, "服务器异常", Toast.LENGTH_SHORT).show();
                });
                return;
            }
            if(jsonResponse.getInteger("status")== HttpURLConnection.HTTP_OK){
                List value = (List) jsonResponse.get("value");
                for (Object o : value) {
                    Map o1 = (Map) o;
                    billList.add(new Bill(Integer.parseInt(o1.get("id").toString()), Byte.parseByte(o1.get("direction").toString()), Float.parseFloat(o1.get("amount").toString()), o1.get("orderformId").toString(), LocalDateTime.parse(o1.get("createTime").toString())));
                }
                handler.post(() -> {
                    billAdapter.notifyDataSetChanged();
                    listviewBill.setVisibility(value.size() > 0 ? View.VISIBLE : View.GONE);
                    payment_listLoading.setVisibility(View.GONE);
                    //如果获取的是0条数据，则显示 txtNoData
                    txtNoData.setVisibility(value.size() == 0 ? View.VISIBLE : View.GONE);
                });
            }else {
                handler.post(()->{
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                    finish();
                });
            }
        });
        thread.start();


    }
    public synchronized void sumTotal(JSONObject jsonObject, Map<String, String> header,TextView paymentTxt,String url){
        new Thread(() -> {
            String post = HttpUtils.post("/api/bills/"+url, header, jsonObject.toJSONString());
            JSONObject jsonResponse = JSONObject.parseObject(post);
            if(jsonResponse.getInteger("status")== HttpURLConnection.HTTP_OK){
                handler.post(() -> {
                    paymentTxt.setText(jsonResponse.get("value").toString());
                });
            }else {
                handler.post(() -> {
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                    finish();
                });
            }
        }).start();
    }
}